//https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* dfs(vector<int>& inorder,vector<int>& postorder,int &p,int inbegin,int inend)
    {
        if(inbegin>inend)
        return NULL;

        TreeNode* root=new TreeNode(postorder[p]);
        int rooti=inbegin;
        while(rooti<=inend)
        {
            if(postorder[p]==inorder[rooti])
            break;
            else
            rooti++;
        }

        p--;
        //递归创建左右子树
        root->right=dfs(inorder,postorder,p,rooti+1,inend);
        root->left=dfs(inorder,postorder,p,inbegin,rooti-1);

        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) 
    {
        int i=postorder.size()-1;
        return dfs(inorder,postorder,i,0,postorder.size()-1);
    }
};

//https://leetcode.cn/problems/construct-string-from-binary-tree/description/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    string tree2str(TreeNode* root) 
    {
        string ret;
        if(root==nullptr)
        return "";

        ret+=to_string(root->val);
        if(root->left || root->right)
        {
            ret+='(';
            ret+=tree2str(root->left);
            ret+=')';
        }    

        if(root->right)
        {
            ret+='(';
            ret+=tree2str(root->right);
            ret+=')';
        }

        return ret;
    }
};